package com.example.qu_tao.View;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.qu_tao.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GouWuCheActivity extends AppCompatActivity {
    private ListView lvCartItems;
    private CheckBox cbSelectAll;
    private TextView tvTotalPrice;
    private Button btnSettleAccounts;
    private List<Map<String, Object>> cartList;
    private SimpleAdapter adapter;
    private List<Boolean> isCheckedList;

    @Override
    @SuppressLint("Range")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gouwuche);

        // 设置Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 返回上一页
            }
        });

        lvCartItems = findViewById(R.id.lv_cart_items);
        cbSelectAll = findViewById(R.id.cb_select_all);
        tvTotalPrice = findViewById(R.id.tv_total_price);
        btnSettleAccounts = findViewById(R.id.btn_settle_accounts);

        cartList = new ArrayList<>();
        isCheckedList = new ArrayList<>();

        // 从购物车表中查询商品信息
        ContentResolver contentResolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.qu_tao.provider/cart");
        String[] projection = {"goods_name", "goods_price"};
        Cursor cursor = contentResolver.query(uri, projection, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String goodsName = cursor.getString(cursor.getColumnIndex("goods_name"));
                double goodsPrice = cursor.getDouble(cursor.getColumnIndex("goods_price"));
                Map<String, Object> item = new HashMap<>();
                item.put("goods_name", goodsName);
                item.put("goods_price", goodsPrice);
                item.put("goods_count", 1); // 初始化商品数量为1
                cartList.add(item);
                isCheckedList.add(false);
            }
            cursor.close();
        }

        adapter = new SimpleAdapter(this, cartList, R.layout.item_cart,
                new String[]{"goods_name", "goods_price", "goods_count"},
                new int[]{R.id.tv_item_goods_name, R.id.tv_item_goods_price, R.id.tv_item_goods_count}) {
            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                CheckBox cbItemSelect = view.findViewById(R.id.cb_item_select);
                TextView tvGoodsCount = view.findViewById(R.id.tv_item_goods_count);
                Button btnMinus = view.findViewById(R.id.btn_minus);
                Button btnPlus = view.findViewById(R.id.btn_plus);

                cbItemSelect.setChecked(isCheckedList.get(position));
                cbItemSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        isCheckedList.set(position, isChecked);
                        calculateTotalPrice();
                        updateSelectAllStatus();
                    }
                });

                btnMinus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int count = (int) cartList.get(position).get("goods_count");
                        if (count > 1) {
                            count--;
                            cartList.get(position).put("goods_count", count);
                            tvGoodsCount.setText(String.valueOf(count));
                            calculateTotalPrice();
                        }
                    }
                });

                btnPlus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int count = (int) cartList.get(position).get("goods_count");
                        count++;
                        cartList.get(position).put("goods_count", count);
                        tvGoodsCount.setText(String.valueOf(count));
                        calculateTotalPrice();
                    }
                });

                return view;
            }
        };

        lvCartItems.setAdapter(adapter);

        cbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (int i = 0; i < isCheckedList.size(); i++) {
                    isCheckedList.set(i, isChecked);
                }
                adapter.notifyDataSetChanged();
                calculateTotalPrice();
            }
        });

        btnSettleAccounts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理结算逻辑
                Toast.makeText(GouWuCheActivity.this, "结算成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void calculateTotalPrice() {
        double totalPrice = 0;
        for (int i = 0; i < cartList.size(); i++) {
            if (isCheckedList.get(i)) {
                double price = (double) cartList.get(i).get("goods_price");
                int count = (int) cartList.get(i).get("goods_count");
                totalPrice += price * count;
            }
        }
        tvTotalPrice.setText("总价: ¥" + String.format("%.2f", totalPrice));
    }

    private void updateSelectAllStatus() {
        boolean allChecked = true;
        for (boolean isChecked : isCheckedList) {
            if (!isChecked) {
                allChecked = false;
                break;
            }
        }
        cbSelectAll.setChecked(allChecked);
    }
}